package edu.udel.libra.model.repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import edu.udel.libra.model.FantasyTeam;

@Component
public class JdbcFantasyTeamRepository extends JdbcRepository implements FantasyTeamRepository 
{
	private JdbcTemplate jdbcTemplate;
	private PlayerRepository playerRepository;
	private List<FantasyTeam> fantasyTeams;
	
	public JdbcFantasyTeamRepository() {
		// TODO: Add database connection
		playerRepository = new JdbcPlayerRepository();
		
		// Sample data
		fantasyTeams = new ArrayList<FantasyTeam>();

		FantasyTeam team1 = new FantasyTeam();
		team1.setLeagueId(0);
		team1.setId(0);
		team1.setName("The Good's Team");
		team1.setPlayers(playerRepository.getPlayersForTeam(team1.getId(), team1.getLeagueId()));
		
		FantasyTeam team2 = new FantasyTeam();
		team2.setLeagueId(0);
		team2.setId(1);
		team2.setName("The Bad's Team");
		team2.setPlayers(playerRepository.getPlayersForTeam(team2.getId(), team2.getLeagueId()));
		
		fantasyTeams.add(team1);
		fantasyTeams.add(team2);
		// endof Sample data
	}
	
	public JdbcFantasyTeamRepository(DataSource dataSource) {
		jdbcTemplate = new JdbcTemplate(dataSource);
		playerRepository = new JdbcPlayerRepository(dataSource);
	}
	
	private class FantasyTeamRowMapper implements RowMapper<FantasyTeam> 
	{
        @Override
        public FantasyTeam mapRow(ResultSet rs, int rowNum) throws SQLException {   	
        	FantasyTeam fantasyTeam = new FantasyTeam();
        	fantasyTeam.setId(rs.getInt("ID"));
        	fantasyTeam.setName(rs.getString("NAME"));
        	fantasyTeam.setLeagueId(rs.getInt("LEAGUE_ID"));
            
        	fantasyTeam.setPlayers(playerRepository.getPlayersForTeam(fantasyTeam.getId(), fantasyTeam.getLeagueId()));
     
            return fantasyTeam;
        }
    }

	@Override
	public FantasyTeam getTeam(long teamId, long leagueId) {
		return fantasyTeams.get((int) teamId);
	}

	@Override
	public List<FantasyTeam> getTeamsForLeague(long leagueId) {
		List<FantasyTeam> leagueTeams = new ArrayList<FantasyTeam>();
		for (FantasyTeam t: fantasyTeams) {
			if (t.getLeagueId() == leagueId)
				leagueTeams.add(t);
		}
		
		return leagueTeams;
	}

}
